﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using FluidKit.Helpers.DragDrop;

namespace WIAssistant
{
    /// <summary>
    /// Used to drag a DestinationField.
    /// </summary>
    public class DestinationFieldDragSourceAdvisor : IDragSourceAdvisor
    {
        private readonly bool _isComingFromSource;
        private static readonly DataFormat _supportedFormat = DataFormats.GetDataFormat("FluidKit2");

        public DestinationFieldDragSourceAdvisor(bool isComingFromSource)
        {
            _isComingFromSource = isComingFromSource;
        }

        public DataObject GetDataObject(UIElement draggedElt)
        {
            DestinationField destinationField;
            if (_isComingFromSource)
                destinationField = (DestinationField) ((ContentControl) draggedElt).Content;
            else
                destinationField = (DestinationField) ((ContentControl) draggedElt).DataContext;
            
            string serializedObject = XamlWriter.Save(destinationField.DestField.Id);
            DataObject data = new DataObject(_supportedFormat.Name, serializedObject);

            return data;
        }

        public void FinishDrag(UIElement draggedElt, DragDropEffects finalEffects)
        {
            if ((finalEffects & DragDropEffects.Move) == DragDropEffects.Move)
            {
                Panel panel = SourceUI as Panel;
                if (panel != null)
                {
                    panel.Children.Remove(draggedElt);
                }
            }
        }

        public bool IsDraggable(UIElement dragElt)
        {
            return (dragElt is ContentControl);
        }

        public UIElement GetTopContainer()
        {
            return Application.Current.MainWindow.Content as UIElement;
        }

        public UIElement SourceUI { get; set; }

        public DragDropEffects SupportedEffects
        {
            get { return DragDropEffects.Copy | DragDropEffects.Move; }
        }
    }
}
